import Vue from 'vue'
import VueRouter from 'vue-router'
//引入仓库
import store from '../store'
//封装一个函数  用户判断是否含有该权限 如果含有就next 如果没有就返回url 路由地址
function hasUrl(url, next) {
  let result = store.getters.getUser.menus_url.some(item => item == url)
  if (result) {
    next()
  } else {
    //没有权限就强制跳转到首页
    next('/home')
  }
}


Vue.use(VueRouter)
export const routesIndex = [{
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/menu', next)
    }
  }, {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/menu', next)
    }
  }, {
    path: '/user',
    component: () => import('../views/admin/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter(to, from, next) {
      hasUrl('/menu', next)
    }
  }, {
    path: '/cate',
    component: () => import('../views/cate/cate.vue'),
    meta: {
      title: '商品分类管理'
    }
  },
  {
    path: "/specs",
    component: () => import("../views/goodsspecs/goodsspecs.vue"),
    meta: {
      title: "商品规格管理",
    },
  },
  {
    path: "/goods",
    component: () => import("../views/goods/goods.vue"),
    meta: {
      title: "商品管理",
    },
  },{
    path:"/member",
    component:() =>import ("../views/member/member.vue"),
    meta:{
      title:"会员管理"
    }
  },
  {
    path:"/banner",
    component:() =>import ("../views/banner/banner.vue"),
    meta:{
      title:"轮播图管理"
    }
  },
  {
    path:"/seckill",
    component:() =>import ("../views/seckill/seckill.vue"),
    meta:{
      title:"秒杀活动"
    }
  }
]


const routes = [{
    path: '/login',
    component: () => import('../pages/login.vue'),
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [{
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...routesIndex,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  { //二级路由重定向
    path: '*',
    redirect: '/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//调用全局前置导航守卫
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
    return
  }
  //如果已经登录 就放行
  if (store.getters.getUser) {
    next()
    return
  }
  //以上条件都不符合 就直接强制跳转到登录
  next('/login')
})


export default router